package cn.byapps.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.byapps.core.utils.DecryptUtil;
import cn.byapps.entity.User;
import cn.byapps.entity.vo.Result;
import cn.byapps.service.UserService;

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("api")
public class GenealogyController {

	@Resource
	private UserService userService;

	@ResponseBody
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public Result login(String username, String password, HttpSession session) {
		// System.out.println(session.getId());
		Result res = new Result();

		User u = userService.login(username, DecryptUtil.MD5(username + password));
		if (u != null) {
			//1.28 若妻子登录，则显示丈夫的族谱
			if (u.getCoupleId() != null && u.getSex() != null && u.getSex().equals("女")) {
				session.setAttribute("topId", u.getCoupleId());
			} else {
				session.setAttribute("topId", u.getId());
			}
			session.setAttribute("loginUser", u);
			res.setCode(200);
			res.setMessage("登录成功");
			res.setToken("" + u.getId());
		} else {
			session.removeAttribute("topId");
			session.removeAttribute("loginUser");
			res.setCode(500);
			res.setMessage("用户名或密码不正确");
		}
		return res;
	}
	/**
	 * 用户注册 result
	 */
	@ResponseBody
	@RequestMapping(value = "result", method = RequestMethod.POST)
	public Result register(String loginName,String name, String password,String sex, HttpSession session) {
		Result res = new Result();
		User user = userService.findByLoginName(loginName);
		if (user != null) {
			res.setCode(500);
			res.setMessage("登录名已注册");
		} else {
			User u = new User();
			u.setLoginName(loginName);
			u.setName(name);
			u.setSex(sex);
			u.setPwd(DecryptUtil.MD5(loginName + password));
			u = userService.save(u);
			if (u != null) {
				res.setCode(200);
				res.setMessage("注册成功");
			} else {
				res.setCode(500);
				res.setMessage("注册失败");
			}
		}
		return res;
	}
	@ResponseBody
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public Result logout(HttpSession session) {
		// System.out.println(session.getId());
		Result res = new Result();
		res.setCode(200);
		res.setMessage("退出成功");
		return res;
	}

	/**
	 * 获取自己以下的家族树
	 * 
	 * @param token
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "genealogy", method = RequestMethod.POST)
	public Result getGenealogy(String token, HttpSession session) {
		// System.out.println(session.getId());
		Result res = new Result();
		User u = userService.get(token);
		res.setData(u);
		res.setCode(200);
		res.setMessage("成功");
		return res;
	}

	/**
	 * 获取自己家族树
	 * 
	 * @param token
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "genealogyall", method = RequestMethod.POST)
	public Result getAllGenealogy(String token, HttpSession session) {
		// System.out.println(session.getId());
		Result res = new Result();
		User u = userService.getParent(token);
		res.setData(u);
		res.setCode(200);
		res.setMessage("成功");
		return res;
	}

	/**
	 * 用户注册 reg
	 */
	@ResponseBody
	@RequestMapping(value = "genealogyreg", method = RequestMethod.POST)
	public Result reg(User user, HttpSession session) {
		Result res = new Result();
		if (user.getLoginName() != null && !"".equals(user.getLoginName())) {
			User us = userService.findByLoginName(user.getLoginName());
			if (us != null) { // 唯一
				res.setCode(500);
				res.setMessage(us.getId().toString());
				return res;
			}
		} else {
			user.setLoginName(null);
		}
		user.setPwd(DecryptUtil.MD5(user.getLoginName() + user.getPwd()));
		user = userService.save(user);
		res.setCode(200);
		res.setMessage(user.getId().toString());
		return res;
	}

	/**
	 * 用户注册 reg
	 */
	@ResponseBody
	@RequestMapping(value = "genealogyaddchild", method = RequestMethod.POST)
	public Result addDown(User user, String token, HttpSession session) {
		Result res = new Result();

		/*if (!"".equals(token)) {
			User parent = userService.get(token);
			if (parent == null) {
				res.setCode(500);
				res.setMessage("找不到父亲");
			} else {
				user.setParent(parent);
				user.setPwd(DecryptUtil.MD5(user.getLoginName() + user.getPwd()));
				if (user.getLoginName() != null && !"".equals(user.getLoginName())) {
					User us = userService.findByLoginName(user.getLoginName());
					if (us != null) { // 唯一
						res.setCode(201);
						res.setMessage(us.getLoginName() + " 已经使用！请重新输入");
						return res;
					}
				} else {
					user.setLoginName(null);
				}
				user = userService.save(user);
				res.setCode(200);
				res.setMessage("成功");
			}
		} else {
			res.setCode(500);
			res.setMessage("token为空");
		}
		*/
		//1-23 修改
		if (!"".equals(token)) {
			User parent = userService.get(token);
			if (parent == null) {
				res.setCode(500);
				res.setMessage("找不到父亲");
			} else {
				User me = userService.getById(user.getId());
				if(me == null) {
					res.setCode(500);
					res.setMessage("找不到ID为" + user.getId() + " 的用户信息");
				} else if(!me.getPwd().equals(DecryptUtil.MD5(me.getLoginName() + user.getPwd()))) {
					res.setCode(500);
					res.setMessage("ID为" + user.getId() + " 的用户,密码不正确");
				} else if(me.getId().intValue() == parent.getId().intValue()) {
					res.setCode(500);
					res.setMessage("不能添加自己");
				}else if(me.getParent()!=null) {
					res.setCode(500);
					res.setMessage("ID为"+ user.getId() + " 已经有上辈了，上辈为" + me.getParent().getName());	
				}else if(userService.checkUser(parent,me)) {
					res.setCode(500);
					res.setMessage("已经存在关系，不能添加！");
				}
				else {
					me.setParent(parent);
					userService.update(me);
					res.setCode(200);
					res.setMessage("成功");
				}
			}
		} else {
			res.setCode(500);
			res.setMessage("token为空");
		}
		return res;
	}

	@ResponseBody
	@RequestMapping(value = "genealogyaddparent", method = RequestMethod.POST)
	public Result addUp(User user, String token, HttpSession session) {
		Result res = new Result();
		/*if (!"".equals(token)) {
			User parent = userService.get(token);
			if (parent.getParent() == null) {
				user.setPwd(DecryptUtil.MD5(user.getLoginName() + user.getPwd()));
				if (user.getLoginName() != null && !"".equals(user.getLoginName())) {
					User us = userService.findByLoginName(user.getLoginName());
					if (us != null) { // 唯一
						res.setCode(201);
						res.setMessage(us.getLoginName() + " 已经使用！请重新输入");
						return res;
					}
				} else {
					user.setLoginName(null);
				}
				user = userService.save(user);
				parent.setParent(user);
				userService.update(parent);
				res.setCode(200);
				res.setMessage("成功");
			} else {
				res.setCode(500);
				res.setMessage("已经有上辈了，上辈为" + parent.getParent().getName());
			}
		}*/
		//1-23 修改 
		if (!"".equals(token)) {
			User parent = userService.get(token);
			if (parent.getParent() == null) {
				User me = userService.getById(user.getId());
				if(me == null) {
					res.setCode(500);
					res.setMessage("找不到ID为" + user.getId() + " 的用户信息");
				} else if(!me.getPwd().equals(DecryptUtil.MD5(me.getLoginName() + user.getPwd()))) {
					res.setCode(500);
					res.setMessage("ID为" + user.getId() + " 的用户,密码不正确");
				} else if(me.getId().intValue() == parent.getId().intValue()) {
					res.setCode(500);
					res.setMessage("不能添加自己");
				} else if(userService.checkUser(parent,me)) {
					res.setCode(500);
					res.setMessage("已经存在关系，不能添加！");
				}
				else {
					parent.setParent(me);
					userService.update(parent);
					res.setCode(200);
					res.setMessage("成功");
				}
			} else {
				res.setCode(500);
				res.setMessage("已经有上辈了，上辈为" + parent.getParent().getName());
			}
		}
		return res;
	}

	@ResponseBody
	@RequestMapping(value = "genealogyaddcouple", method = RequestMethod.POST)
	public Result addCouple(User user, String token, HttpSession session) {
		
		Result res = new Result();
		/*if (!"".equals(token)) {
			User parent = userService.get(token);
			if (parent.getCoupleId() == null) {
				user.setCoupleId(parent.getId());
				user.setCoupleName(parent.getName());
				user.setPwd(DecryptUtil.MD5(user.getLoginName() + user.getPwd()));
				if (user.getLoginName() != null && !"".equals(user.getLoginName())) {
					User us = userService.findByLoginName(user.getLoginName());
					if (us != null) { // 唯一
						res.setCode(201);
						res.setMessage(us.getLoginName() + " 已经使用！请重新输入");
						return res;
					}
				} else {
					user.setLoginName(null);
				}
				user = userService.save(user);
				parent.setCoupleId(user.getId());
				parent.setCoupleName(user.getName());
				userService.update(parent);
				res.setCode(200);
				res.setMessage("成功");
			} else {
				res.setCode(500);
				res.setMessage("已经有配偶了，配偶为" + parent.getCoupleName());
			}
		}*/
		//1-23 修改 
		if (!"".equals(token)) {
			User parent = userService.get(token);
			
			if (parent.getCoupleId() == null) {
				User me = userService.getById(user.getId());
				if(me == null) {
					res.setCode(500);
					res.setMessage("找不到ID为" + user.getId() + " 的用户信息");
				} else if(!me.getPwd().equals(DecryptUtil.MD5(me.getLoginName() + user.getPwd()))) {
					res.setCode(500);
					res.setMessage("ID为" + user.getId() + " 的用户,密码不正确");
				} else if(me.getId().intValue() == parent.getId().intValue()) {
					res.setCode(500);
					res.setMessage("不能添加自己");
				} else if(parent.getCoupleId()!=null) {
					res.setCode(500);
					res.setMessage("已经有配偶了，不能添加");
				}else if(parent.getSex()!=null && parent.getSex().equals(me.getSex())) {
					res.setCode(500);
					res.setMessage("性别相同，不能添加");
				}
				else {
					me.setCoupleId(parent.getId());
					me.setCoupleName(parent.getName());
					parent.setCoupleId(me.getId());
					parent.setCoupleName(me.getName());
					userService.update(parent);
					userService.update(me);
					res.setCode(200);
					res.setMessage("成功");
				}
			} else {
				res.setCode(500);
				res.setMessage("已经有配偶了，配偶为" + parent.getCoupleName());
			}
		}
		return res;
	}

	/**
	 * 用户删除
	 */
	@ResponseBody
	@RequestMapping(value = "genealogydelete", method = RequestMethod.POST)
	public Result delete(User user, HttpSession session) {
		Result res = new Result();
		User u = (User) session.getAttribute("loginUser");
		if (u == null) {
			res.setCode(501);
			res.setMessage("请重新登录");
		} else if (u.getId().intValue() == user.getId().intValue()) {
			res.setCode(502);
			res.setMessage("不能删除自己");
		} else {
			boolean del = userService.delete(user);
			if (del) {
				res.setCode(200);
				res.setMessage("成功");
			} else {
				res.setCode(500);
				res.setMessage("无法删除，他有后代");
			}
		}

		return res;
	}

	/**
	 * 用户修改
	 */
	@ResponseBody
	@RequestMapping(value = "genealogyget", method = RequestMethod.POST)
	public Result get(User user, HttpSession session) {
		Result res = new Result();
		User u = userService.get(user.getId().toString());
		if (u != null) {
			res.setCode(200);
			res.setMessage("成功");
			res.setData(u);
		} else {
			res.setCode(500);
			res.setMessage("找不到");
		}
		return res;
	}

	/**
	 * 用户修改
	 */
	@ResponseBody
	@RequestMapping(value = "genealogyupdate", method = RequestMethod.POST)
	public Result update(User user, HttpSession session) {
		Result res = new Result();
		User oldUser = userService.get(user.getId().toString());
		if (user.getPwd() != null && !user.getPwd().equals("")) {
			oldUser.setPwd(DecryptUtil.MD5(user.getLoginName() + user.getPwd()));
		}
		if (user.getLoginName() != null) {
			oldUser.setLoginName(user.getLoginName());
		}
		if (user.getTelephone() != null && !user.getTelephone().equals("")) {
			oldUser.setTelephone(user.getTelephone());
		}
		if (user.getName() != null && !user.getName().equals("")) {
			oldUser.setName(user.getName());
		}
		if (user.getSex() != null && !user.getSex().equals("")) {
			oldUser.setSex(user.getSex());
		}
		// 修改无法更新问题
		if (user.getLoginName() != null && !"".equals(user.getLoginName())) {
			User us = userService.findByLoginName(user.getLoginName());
			if (us != null && !us.getId().equals(user.getId())) { // 唯一
				res.setCode(201);
				res.setMessage(us.getLoginName() + " 已经使用！请重新输入");
				return res;
			}
		} else {
			user.setLoginName(null);
		}
		userService.update(oldUser);
		res.setCode(200);
		res.setMessage("成功");

		return res;
	}
}
